package com.xl98.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xl98.entity.*;
import com.xl98.mapper.UserMapper;
import com.xl98.service.LoginService;
import com.xl98.service.UserService;
import com.xl98.service.sendMailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ls
 * @since 2020-05-15
 */
@Api(value="用户",tags = {"用户"})
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private sendMailService sendMailService;
    @Autowired
    private LoginService loginService;
    /**
     * 登录方法
     */
    @ResponseBody
    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result Login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            return ResultFactory.buildSuccessResult(token);
        } catch (IncorrectCredentialsException e) {
            return ResultFactory.buildFailResult(ResponseCode.WRONG_PASSWORD);
        }  catch (AuthenticationException e) {
            return ResultFactory.buildFailResult(ResponseCode.NOT_USER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultFactory.buildFailResult(ResponseCode.FAIL_LOGIN);
    }

    @ResponseBody
    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Result Logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultFactory.buildSuccessResult(ResponseCode.SUCCESS_LOGOUT);
    }



    /*
     * 未登录，shiro重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     */
    @RequestMapping(value = "/unauth")
    @ApiOperation(value = "未登录")
    @ResponseBody
    public Result unauth() {
        return ResultFactory.buildFailResult(ResponseCode.NOT_LOGIN);
    }

    //注册的邮箱
    private String RegistEmail=null;
    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/email", method = RequestMethod.POST)
    @ApiOperation(value = "邮箱验证码")
    public Result send (String email, HttpServletRequest request){
        String VerificationCode = String.valueOf(new Random().nextInt(9000) + 1000);
        System.out.println(VerificationCode);
        RegistEmail = email;
        sendMailService.sendMail(ResponseCode.REGIST_EMAIL_SUBJECT,ResponseCode.REGIST_EMAIL_TEXT + VerificationCode,email);
        HttpSession session = request.getSession();
        session.setAttribute("code", VerificationCode);
        try {
            final Timer timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    String code = (String) session.getAttribute("code");
                    if(StringUtils.checkValNotNull(code)){
                        session.removeAttribute("code");
                        RegistEmail = null;
                        System.out.println("验证码失效了");
                    }
                    timer.cancel();
                }
            },5*60*1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultFactory.buildSuccessResult(ResponseCode.SUCCESS_MESSAGE);
    }

    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/verifyemail", method = RequestMethod.POST)
    @ApiOperation(value = "判断邮箱是否已经被注册")
    public Result verifyemail (@RequestBody Map<String, String> map) throws ParseException {
        User user = userService.findByString(map);
        if(StringUtils.checkValNull(user)){
            return ResultFactory.buildSuccessResult(ResponseCode.SUCCESS_VERIFY_EMAIL);
        }
        else{
            return ResultFactory.buildFailResult(ResponseCode.FAIL_VERIFY_EMAIL);
        }
    }
    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    @ApiOperation(value = "用户注册")
    public Result Regist (@RequestBody Map<String, String> map,HttpServletRequest request) throws ParseException {
        String code = (String) request.getSession().getAttribute("code");
        if(StringUtils.checkValNull(code)){
            return ResultFactory.buildFailResult(ResponseCode.NOT_CODE);
        }
        else{
            if(map.get("code").equals(code)&&RegistEmail.equals(map.get("email"))){
                User user = new User();
                user.setUsername(map.get("username"));
                user.setPassword(map.get("password"));
                user.setEmail(map.get("email"));
                int rs = userService.regist(user);
                if(rs>0){
                    return ResultFactory.buildSuccessResult(ResponseCode.SUCCESS_REGIST);
                }
                else  return ResultFactory.buildFailResult(ResponseCode.FAIL_REGIST);
            }
            else{
                return ResultFactory.buildFailResult(ResponseCode.WRONG_CODE);
            }
        }
    }

    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/all", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有用户")
    public Result findAllUser() {
        List<User> userList = userService.findAllUser();
        return ResultFactory.buidResult(ResponseCode.SUCCESS_CODE,ResponseCode.SUCCESS_FIND,userList);
    }

    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/one", method = RequestMethod.POST)
    @ApiOperation(value = "根据ID或名字或邮箱查询用户")
    public Result findByString (@RequestBody Map<String, String> map) throws ParseException {
        User user = userService.findByString(map);
        if(StringUtils.checkValNotNull(user)){
            return ResultFactory.buidResult(ResponseCode.SUCCESS_CODE,ResponseCode.SUCCESS_FIND,user);
        }
        else{
            return ResultFactory.buidResult(ResponseCode.FAIL_CODE,ResponseCode.FAIL_FIND,user);
        }
    }

    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/userRole", method = RequestMethod.POST)
    @ApiOperation(value = "根据角色类型查询用户")
    public Result findAllConsultant(String roleId)  {
        List<User> userList = userService.findAllByRole(roleId);
        if(StringUtils.checkValNotNull(userList)){
            return ResultFactory.buidResult(ResponseCode.SUCCESS_CODE,ResponseCode.SUCCESS_FIND,userList);
        }
        else{
            return ResultFactory.buildFailResult(ResponseCode.FAIL_FIND);
        }
    }
    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/updateuser", method = RequestMethod.POST)
    @ApiOperation(value = "更新用户")
    public Result updateUser (@RequestBody Map<String, String> map) throws ParseException {
        User user = new User();
        user.setId(map.get("id"));
        user.setUsername(map.get("username"));
        user.setPassword(map.get("password"));
        user.setEmail(map.get("email"));
        user.setTelephone(map.get("telephone"));
        user.setSex(map.get("sex"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = simpleDateFormat.parse(map.get("birthday"));
        user.setBirthday(birthday);
        user.setHeadPortrait(map.get("headPortrait"));
        user.setSignaTure(map.get("signaTure"));
        int res = userService.updateUser(user);
        if(res>0){
            HashMap<String, String> usermap = new HashMap<>();
            usermap.put("id",map.get("id"));
            return ResultFactory.buidResult(ResponseCode.SUCCESS_CODE,ResponseCode.SUCCESS_UPDATE,userService.findByString(usermap));
        }
        else{
            return ResultFactory.buildFailResult(ResponseCode.FAIL_UPDATE);
        }
    }
    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/userstate", method = RequestMethod.POST)
    @ApiOperation(value = "更新用户状态")
    public Result updateUserState (@RequestBody Map<String, String> map) throws ParseException {
        int rs = userService.updateUserState(map);
        if(rs>0){

            return ResultFactory.buidResult(ResponseCode.SUCCESS_CODE,ResponseCode.SUCCESS_UPDATE,userService.findByString(map));
        }
        else{
            return ResultFactory.buildFailResult(ResponseCode.FAIL_UPDATE);
        }
    }
    @ResponseBody
    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ApiOperation(value = "用户权限")
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public Result info(UsernamePasswordToken token) {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", token.getUsername());
        LoginInfo loginInfo = loginService.getLoginInfo(map);
        return ResultFactory.buildSuccessResult(loginInfo);// 将用户的角色和权限发送到前台
    }

/*    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/selectUserByRole", method = RequestMethod.POST)
    @ApiOperation(value = "根据角色查询用户")
    public Result selectUserByRole(String roleId){
        List<User> list = userService.findByRole(roleId);
        return ResultFactory.buildSuccessResult(list);
    }*/

  /*  @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
    @ResponseBody
    @RequestMapping(value = "/code", method = RequestMethod.POST)
    @ApiOperation(value = "测试验证码")
    public String testCode (HttpServletRequest request){
        if(StringUtils.checkValNotNull(request.getSession().getAttribute("code"))){
            return (String) request.getSession().getAttribute("code");
        }
        else{
            return "验证码失效";
        }
    }*/
}

